/**
 * 
 */
package com.wgo.bpot.common.transport.servicefacade.hessian;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;


import com.caucho.hessian.io.AbstractDeserializer;
import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;
import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.Deserializer;
import com.caucho.hessian.io.Serializer;
import com.wgo.bpot.common.transport.util.Assert;

/**
 * Due to hessian incompability.
 * 
 * @author petterei
 * @version $Id: UrlSerializerFactory.java,v 1.1 2006-03-07 19:45:52 petterei Exp $
 */
public class UrlSerializerFactory extends AbstractSerializerFactory {
	private static final Logger log = Logger.getLogger(UrlSerializerFactory.class.getName());
	
	private UrlSerializer methodSerializer = new UrlSerializer();
	
	private UrlDeserializer methodDeserializer = new UrlDeserializer();
	
	@Override
	public Serializer getSerializer(Class cl) {
		
		if (log.isLoggable(Level.FINER)) {
			log.log(Level.FINER, "Looking up serializer for: " + cl.getName());
		}
		if (URL.class.isAssignableFrom(cl)) {
			if (log.isLoggable(Level.FINER)) {
				log.log(Level.FINER, "Returning method serializer for class: " + cl.getName());
			}
			return methodSerializer;
		}
		
		return null;
	}
	
	@Override
	public Deserializer getDeserializer(Class cl) {
		
		if (log.isLoggable(Level.FINER)) {
			log.log(Level.FINER, "Looking up deserializer for: " + cl.getName());
		}
		if (Method.class.isAssignableFrom(cl)) {
			if (log.isLoggable(Level.FINER)) {
				log.log(Level.FINER, "Returning method deserializer for class: " + cl.getName());
			}
			return methodDeserializer;
		}
		return null;
	}
}
class UrlSerializer extends AbstractSerializer {
	private static final Logger log = Logger.getLogger(UrlSerializer.class.getName());
	
	@Override
	public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
		URL url = (URL)obj;
		String externalForm = url.toExternalForm();
		log.fine("Writing url " + externalForm );
		out.writeMapBegin(externalForm);
		out.writeString(externalForm);
		out.writeMapEnd();
	}
}
class UrlDeserializer extends AbstractDeserializer {
	
	private static final Logger log = Logger.getLogger(UrlDeserializer.class.getName());
	
	@Override
	public Object readMap(AbstractHessianInput in) throws IOException {
		String externalForm = null;
		while (!in.isEnd()) {
			externalForm = in.readString();
		}
		in.readMapEnd();
		Assert.assertNotNull(externalForm, getClass().getSimpleName() +" Expected URL external form representation.");
		log.fine("Reading url " + externalForm );
		URL url = null;
		url = new URL(externalForm);
		return url;
	}
}